package com.xspace.android.imcommon.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.text.TextUtils;
import android.util.Log;

import com.xspace.android.imcommon.entity.MucRoomBean;

import java.util.ArrayList;

/**
 * 群聊数据表
 * @author Administrator
 *
 */
public class RoomDB extends BaseDb{
	public RoomDB(Context context){
		super(context);
	}
	public static final String TAG = "RoomDB";
	/**
	 * _id
	 */
	public static final String _ID = "_id";
	public static final String COLOUMN_CREATE_TIME = "create_time";
	/**
	 * 创建者
	 */
	public static final String COLOUMN_Creater = "creater";
	public static final String COLOUMN_Creater_Jid = "create_jid";
	public static final String COLOUMN_RoomName = "room_name";
	public static final String COLOUMN_RoomID = "room_id";
	/**type=3 代表roomjid**/
	public static final String COLOUMN_RoomPID = "room_pid";
	/**圈子 1群聊 2多人会话 3xmpp 群组 4环信 圈子5环信 群组 6环信 多人会话 **/
	public static final String COLOUMN_RoomType = "room_type";
	public static final String COLOUMN_RoomProfile = "room_profile";
	public static final String COLOUMN_RoomIco = "room_ico";
	/**
	 * 图片本地存储路径
	 */
	public static final String COLOUMN_IMGPATH = "imgPath";
	public static final String TABLE_NAME = "MUC_ROOM";
	
	public static final String CREATE_TABLE =  "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER primary key, " 
	        + COLOUMN_RoomProfile+ " CHAR(1000)," 
			+ COLOUMN_RoomType + " INTEGER," 
	        + COLOUMN_CREATE_TIME + " CHAR(128),"
			+ COLOUMN_Creater + " CHAR(128),"
			+ COLOUMN_Creater_Jid + " CHAR(128)," 
			+ COLOUMN_RoomName + " CHAR(128), " 
			+ COLOUMN_RoomID + " CHAR(128),"
			+ COLOUMN_RoomPID + " CHAR(128),"
			+ COLOUMN_RoomIco + " CHAR(128)," 
			+ COLOUMN_IMGPATH + " CHAR(128))";
    private Object syncObj=new Object();
	@Override
	String getTableName() {
		return TABLE_NAME;
	}
	
	/**
	 * 保存消息数据
	 * 
	 * @param city
	 * @roomType 圈子 1群聊 2多人会话 3xmpp 群组 4环信 圈子5环信 群组 6环信 多人会话 
	 * @return
	 */
	public int insertOrUpdateMsg(MucRoomBean mucroom) {
		if(mucroom==null)  return -1;
		Log.d(TAG, "insertOrUpdateMsg()... roomdb: " + mucroom.room_name+" pid:"+mucroom.parent_id+" type:"+mucroom.room_type);
		if(mucroom.parent_id==null&&"3".equals(mucroom.room_type)) return -1;
		synchronized (syncObj) {
			ContentValues values = new ContentValues();
			values.put(COLOUMN_Creater, mucroom.creater);
			values.put(COLOUMN_Creater_Jid, mucroom.create_jid);
			values.put(COLOUMN_CREATE_TIME, mucroom.create_time);
			values.put(COLOUMN_IMGPATH, mucroom.imgPath);
			values.put(COLOUMN_RoomIco, mucroom.room_ico);
			values.put(COLOUMN_RoomName, mucroom.room_name);
			if (!TextUtils.isEmpty(mucroom.room_id))
			values.put(COLOUMN_RoomID, mucroom.room_id);
			if (!TextUtils.isEmpty(mucroom.parent_id))
			values.put(COLOUMN_RoomPID, mucroom.parent_id);
			values.put(COLOUMN_RoomProfile, mucroom.room_profile);
			if (!TextUtils.isEmpty(mucroom.room_type))
			values.put(COLOUMN_RoomType, mucroom.room_type);
			String sql = null;
			if ("3".equals(mucroom.room_type)) {
				sql = "select * from " + TABLE_NAME + " where "
						+ COLOUMN_RoomPID + " = '" + mucroom.parent_id + "'";
			} else {
				sql = "select * from " + TABLE_NAME + " where "
						+ COLOUMN_RoomID + " = '" + mucroom.room_id + "'";
			}
			Cursor cursor = null;
			try {
				long rowId = -1;
				checkDb();
				cursor = db.rawQuery(sql, null);
				if (cursor != null && cursor.getCount() > 0) {
					if ("3".equals(mucroom.room_type)) {
						rowId = db.update(TABLE_NAME, values, COLOUMN_RoomPID
								+ "=?", new String[] { mucroom.parent_id });
					} else {
						rowId = db.update(TABLE_NAME, values, COLOUMN_RoomID
								+ "=?", new String[] { mucroom.room_id });
					}
					rowId = 0;
				} else {
					rowId = db.insert(TABLE_NAME, null, values);
					Log.e(TAG, "insertOrUpdateMsg()... insert rowId: " + rowId);
					rowId = 1;
				}
				return (int) rowId;
			} catch (Exception e) {
				e.printStackTrace();
				return -1;
			} finally {
				closeDbAndCursor(cursor);
			}
		}
	}
	/**0圈子 1群聊 2多人会话 3xmpp 群组**/
	public int insertOrUpdateInviteMsg(String room_jid,int type) {
		if(TextUtils.isEmpty(room_jid))  return -1;
		Log.d(TAG, "insertOrUpdateInviteMsg pid:"+room_jid+" type:"+type);
		ContentValues values = new ContentValues();
		values.put(COLOUMN_RoomPID, room_jid);
		values.put(COLOUMN_RoomType, type+"");
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_RoomPID + " = '" + room_jid + "'";
		Cursor cursor = null;
		try {
			long rowId = -1;
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				rowId = db.update(TABLE_NAME, values, COLOUMN_RoomPID  + "=?", new String[] { room_jid });
			} else {
				rowId = db.insert(TABLE_NAME, null, values);
				Log.e(TAG, "insertOrUpdateInviteMsg()... insert rowId: " + rowId);
			}
			return (int) rowId;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			closeDbAndCursor(cursor);
		}
	}
	public MucRoomBean queryOneRoom(String circle_id){
		MucRoomBean mb=null;
		Cursor cursor = null;
		try {
			checkDb();
			String columns[]={COLOUMN_RoomID,COLOUMN_RoomName,COLOUMN_RoomPID,COLOUMN_RoomProfile};
			String[] selectionArgs={circle_id};
			cursor=db.query(TABLE_NAME, columns, COLOUMN_RoomID+"=?", selectionArgs, null, null, null);
			if(cursor.moveToFirst()){
				String id=cursor.getString(0);
				String roomname=cursor.getString(1);
				String roompid=cursor.getString(2);
				String profile=cursor.getString(3);
				mb=new MucRoomBean(id, roompid, roomname);
				mb.room_profile=profile;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeDbAndCursor(cursor);
		}
		return mb;
	}
	public MucRoomBean queryXmRoom(String room_jid,String type){
		MucRoomBean mb=null;
		Cursor cursor = null;
		try {
			checkDb();
			String columns[]={COLOUMN_RoomID,COLOUMN_RoomName,COLOUMN_RoomPID,COLOUMN_RoomProfile};
			String[] selectionArgs={room_jid,type};
			cursor=db.query(TABLE_NAME, columns, COLOUMN_RoomPID+"=? and "+COLOUMN_RoomType+" =?", selectionArgs, null, null, null);
			if(cursor.moveToFirst()){
				String id=cursor.getString(0);
				String roomname=cursor.getString(1);
				String roompid=cursor.getString(2);
				String profile=cursor.getString(3);
				mb=new MucRoomBean(id, roompid, roomname);
				mb.room_profile=profile;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeDbAndCursor(cursor);
		}
		return mb;
	}
	    /**0圈子 1群聊 2多人会话 3xmpp 群组**/
		public ArrayList<MucRoomBean> queryRoomList(int type) {
			ArrayList<MucRoomBean> chatMsgs = new ArrayList<MucRoomBean>();
				String sql = "select * from " + TABLE_NAME +" where "+COLOUMN_RoomType + " =?  order by "+_ID + " desc";
				Log.d(TAG, "queryRoomList()... " + sql);
				Cursor cursor = null;
				try {
					checkDb();
					cursor = db.rawQuery(sql, new String[]{""+type});
					if (cursor != null && cursor.getCount() > 0) {
						cursor.moveToLast();
						for (int i = cursor.getCount() - 1; i >= 0; i--) {
							cursor.moveToPosition(i);
							MucRoomBean entity = parseCursor(cursor);
							chatMsgs.add(entity);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				} finally {
					closeDbAndCursor(cursor);
				}
				return chatMsgs;
		}
		private MucRoomBean parseCursor(Cursor cursor) {
			MucRoomBean mucroom = new MucRoomBean();
			mucroom.id = cursor.getInt(cursor.getColumnIndex(_ID));
			mucroom.create_time = cursor.getString(cursor.getColumnIndex(COLOUMN_CREATE_TIME));
			mucroom.creater = cursor.getString(cursor.getColumnIndex(COLOUMN_Creater));
			mucroom.create_jid = cursor.getString(cursor.getColumnIndex(COLOUMN_Creater_Jid));
			mucroom.room_ico = cursor.getString(cursor.getColumnIndex(COLOUMN_RoomIco));
			mucroom.room_id = cursor.getString(cursor.getColumnIndex(COLOUMN_RoomID));
			mucroom.room_name= cursor.getString(cursor.getColumnIndex(COLOUMN_RoomName));
			mucroom.room_profile = cursor.getString(cursor.getColumnIndex(COLOUMN_RoomProfile));
			mucroom.room_type = cursor.getString(cursor.getColumnIndex(COLOUMN_RoomType));
			mucroom.parent_id=cursor.getString(cursor.getColumnIndex(COLOUMN_RoomPID));
			mucroom.imgPath = cursor.getString(cursor.getColumnIndex(COLOUMN_IMGPATH));
			return mucroom;
		}

	public boolean deleteOneRoomData(String roomid) {
		try {
			checkDb();
			String whereClause = COLOUMN_RoomID + " = ?";
			String[] whereArgs = new String[] { roomid };
			int res = db.delete(TABLE_NAME, whereClause, whereArgs);
			return res > 0;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
		
	public void deleteAllData() {
		checkDb();
		db.delete(TABLE_NAME, null, null);
	}
	/**0圈子 1群聊 2多人会话 3xmpp 群组**/
	public boolean isExistDataByType(int type) {
		String sql = "select * from " + TABLE_NAME + " where "+COLOUMN_RoomType + " =?";
		boolean exist=false;
		 Cursor	cursor=null;
		try {
			checkDb();
	       	cursor=db.rawQuery(sql, new String[]{type+""});
	       	if(cursor!=null&&cursor.getCount()>0){
	       		exist=true;
	       	}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			closeDbAndCursor(cursor);
		}
		Log.d(TAG, "isExistDataByType()... " + exist);
		return exist;
	}
	/**
	 * 
	 * @param roomtype 圈子 1群聊 2多人会话 3xmpp 群组 4环信 圈子5环信 群组 6环信 多人会话 
	 * @return
	 */
	public ArrayList<MucRoomBean>  queryGroupHelperList(int roomtype) {
		String sql = "select * from MUC_ROOM room, MUC_CHAT_MSG  msg where  room.room_id==msg.roomid and room.room_type=?";

		ArrayList<MucRoomBean> roomlist = new ArrayList<MucRoomBean>();
			Log.d(TAG, "queryGroupHelperList()... " + sql);
			Cursor cursor = null;
			try {
				checkDb();
				cursor = db.rawQuery(sql, new String[]{""+roomtype});
				if (cursor != null && cursor.getCount() > 0) {
					cursor.moveToLast();
					for (int i = cursor.getCount() - 1; i >= 0; i--) {
						cursor.moveToPosition(i);
						MucRoomBean entity = parseCursor(cursor);
						Log.d(TAG, "entry " + entity.room_name+" id:"+entity.room_id+" type:"+entity.room_type);
						roomlist.add(entity);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				closeDbAndCursor(cursor);
			}
			return roomlist;
	

	}
}
